<template>
    <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
</template>

<script>
import request from '@/utils/request'
import { parseTime } from '@/utils'
import { Message } from 'element-ui'

export default {
  name: 'exportExcel',
  data() {
    return {
      list: [],
      downloadLoading: false,
      autoWidth: true
    }
  },
  props: ['filename', 'queryPath', 'query', 'tHeader', 'filterVal'],
  created() { },
  methods: {
    fetchData() {
      return request({
        url: this.queryPath,
        method: 'get',
        params: this.query || {}
      })
    },
    handleDownload() {
      if (this.downloadLoading) {
        return
      }
      this.downloadLoading = true
      this.fetchData().then(response => {
        this.list = response.data && response.data.list || []
        this.downExcel()
      })
    },
    downExcel() {
      if (!this.list || !this.list.length) {
        Message({
          message: '没有可下载的报表',
          type: 'error',
          duration: 3 * 1000,
          showClose: true
        })
        this.downloadLoading = false
        return
      }
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = this.tHeader
        const filterVal = this.filterVal
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>


